package com.neurotech.pcc.other

import android.app.Activity
import android.content.Context
import android.text.TextUtils
import android.view.inputmethod.InputMethodManager
import java.math.BigInteger
import java.security.MessageDigest

/**
 * Created by shenhua on 2018/10/9.
 * @author shenhua
 *         Email shenhuanet@126.com
 */
object Utils {

    fun login(context: Context, username: String, password: String) {
        val sharedPreferences = context.getSharedPreferences("config", Context.MODE_PRIVATE)
        val md5 = MessageDigest.getInstance("MD5")
        md5.update(password.toByteArray())
        val result = BigInteger(1, md5.digest()).toString(16).toUpperCase()
        sharedPreferences.edit().putString("name", username).putString("pass", result).apply()
    }

    fun logout(context: Context) {}

    fun isLogin(context: Context): Boolean {
        return getUser(context) != null
    }

    fun getUser(context: Context): User? {
        val sharedPreferences = context.getSharedPreferences("config", Context.MODE_PRIVATE)
        val name = sharedPreferences.getString("name", null)
        val pass = sharedPreferences.getString("pass", null)
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)) {
            return null
        }
        return User(name!!, pass!!)
    }

    fun hideKeyBoard(context: Activity?) {
        val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val focus = context.currentFocus
        if (imm.isActive && focus != null) {
            if (focus.windowToken != null) {
                imm.hideSoftInputFromWindow(focus.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }
    }
}

data class User(var userName: String, var password: String)